package com.kjc.demo.coapserver;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.eclipse.californium.core.CoapResource;
import org.eclipse.californium.core.CoapServer;
import org.eclipse.californium.core.coap.CoAP;
import org.eclipse.californium.core.server.resources.CoapExchange;

public class CoapServerTest
{
    public static void main(String[] args) {
        // 主机为localhost 端口为默认端口5683
        final CoapServer server = new CoapServer();

        // 默认就是udp实现传输层
        server.add(new CoapResource("hello"){
            // 创建一个资源为hello 请求格式为 主机：端口\hello
            @Override
            public void handleGET(CoapExchange exchange) {
            	String name = exchange.getQueryParameter("name");
                //  重写处理GET请求的方法
                exchange.respond(CoAP.ResponseCode.CONTENT, "Hello CoAP!---" + name);
            }
        });

        server.add(new CoapResource("time"){
            // 创建一个资源为time 请求格式为 主机：端口\time
            @Override
            public void handleGET(CoapExchange exchange) {
                Date date = new Date();
                exchange.respond(CoAP.ResponseCode.CONTENT,
                        new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
            }
        });
        // 启动服务
        server.start();
    }
}
